package api

import (
	"github.com/gin-gonic/gin"
	"guard/internal/app/admin/models"
	"guard/internal/errors"
	"guard/internal/request"
	"guard/internal/result"
	"net/http"
)

func scopeAll(c *gin.Context) {

	all, err := adminService.ScopeAll()

	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "ok",
		Data: all,
	})
}

func scopePage(c *gin.Context) {

	// 使用这个绑定，直接报错
	var rp request.Page
	err := c.ShouldBindQuery(&rp)

	if err != nil {
		_ = c.Error(errors.OtherError("错误的分页信息"))
		return
	}

	scopePageObj, err := adminService.ScopePage(rp.Page, rp.PageSize)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.BuildPage{
		Code:  200,
		Msg:   "成功",
		Total: scopePageObj.Total,
		Data:  scopePageObj.Data,
	})
}

func queryScope(c *gin.Context) {

	query := c.Param("query")

	if query == "" || len(query) == 0 {
		_ = c.Error(errors.OtherError("查询条件错误"))
		return
	}

	permission, err := adminService.QueryScope(query)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "ok",
		Data: permission,
	})
}

func addScope(c *gin.Context) {

	var sc models.AuthorityScope
	err := c.ShouldBindJSON(&sc)
	if err != nil {
		_ = c.Error(errors.OtherError("范围参数错误"))
		return
	}

	err = adminService.AddScope(&sc)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	})
}

func removeScope(c *gin.Context) {

	tag := c.Param("tag")

	if tag == "" || len(tag) == 0 {
		_ = c.Error(errors.OtherError("scope标签错误"))
		return
	}

	err := adminService.RemoveScope(tag)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	})
}
